import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './SearchChat.css';

interface Message {
  _id: string;
  from: string;
  to: string;
  message: string;
  messageType: string;
  timestamp: Date;
}

interface SearchChatProps {
  currentUser: {
    username: string;
    image: string;
  };
  selectedUser: {
    username: string;
    image: string;
  };
  onBack: () => void;
  onMessageClick?: (message: Message) => void;
}

const SearchChat: React.FC<SearchChatProps> = ({
  currentUser,
  selectedUser,
  onBack,
  onMessageClick,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<Message[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);
  const [searchError, setSearchError] = useState('');

  // 搜索聊天内容
  const handleSearch = async () => {
    if (!searchQuery.trim()) {
      setSearchResults([]);
      setHasSearched(false);
      return;
    }

    setIsSearching(true);
    setSearchError('');

    try {
      const response = await axios.post(
        'http://localhost:3001/ysx/chat/search',
        {
          keyword: searchQuery.trim(),
          chatId: `${currentUser.username}-${selectedUser.username}`,
        }
      );

      if (response.data.code === 200) {
        setSearchResults(response.data.data);
        setHasSearched(true);
      } else {
        setSearchError(response.data.msg || '搜索失败');
        setSearchResults([]);
      }
    } catch (error) {
      console.error('搜索聊天内容失败:', error);
      setSearchError('搜索失败，请重试');
      setSearchResults([]);
    } finally {
      setIsSearching(false);
    }
  };

  // 处理搜索输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    if (e.target.value.trim() === '') {
      setSearchResults([]);
      setHasSearched(false);
      setSearchError('');
    }
  };

  // 处理回车搜索
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // 格式化时间显示
  const formatTime = (date: Date | string) => {
    const dateObj = new Date(date);
    const now = new Date();
    const diff = now.getTime() - dateObj.getTime();
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return dateObj.toLocaleDateString('zh-CN');
  };

  // 高亮搜索关键词
  const highlightText = (text: string, query: string) => {
    if (!query.trim()) return text;

    const regex = new RegExp(`(${query})`, 'gi');
    const parts = text.split(regex);

    return parts.map((part, index) =>
      regex.test(part) ? (
        <mark key={index} className="search-highlight">
          {part}
        </mark>
      ) : (
        part
      )
    );
  };

  // 处理消息点击
  const handleMessageClick = (message: Message) => {
    if (onMessageClick) {
      onMessageClick(message);
    }
  };

  return (
    <div className="search-chat-container">
      {/* 头部 */}
      <div className="search-header">
        <button className="back-btn" onClick={onBack}>
          ←
        </button>
        <div className="search-title">查找聊天内容</div>
      </div>

      {/* 搜索框 */}
      <div className="search-input-container">
        <div className="search-input-wrapper">
          <input
            type="text"
            value={searchQuery}
            onChange={handleInputChange}
            onKeyPress={handleKeyPress}
            placeholder={`在 ${selectedUser.username} 的聊天中搜索...`}
            className="search-input"
          />
          <button
            className="search-btn"
            onClick={handleSearch}
            disabled={isSearching || !searchQuery.trim()}
          >
            {isSearching ? '搜索中...' : '搜索'}
          </button>
        </div>
      </div>

      {/* 搜索结果 */}
      <div className="search-results">
        {searchError && <div className="search-error">{searchError}</div>}

        {hasSearched && searchResults.length === 0 && !searchError && (
          <div className="no-results">
            <div className="no-results-icon">🔍</div>
            <div className="no-results-text">未找到相关消息</div>
            <div className="no-results-hint">尝试使用不同的关键词</div>
          </div>
        )}

        {searchResults.length > 0 && (
          <div className="results-list">
            <div className="results-header">
              找到 {searchResults.length} 条相关消息
            </div>
            {searchResults.map(message => (
              <div
                key={message._id}
                className="result-item"
                onClick={() => handleMessageClick(message)}
              >
                <div className="result-message">
                  {message.messageType === 'text' ? (
                    <div className="message-text">
                      {highlightText(message.message, searchQuery)}
                    </div>
                  ) : message.messageType === 'image' ? (
                    <div className="message-type">【图片】</div>
                  ) : message.messageType === 'video' ? (
                    <div className="message-type">【视频】</div>
                  ) : message.messageType === 'file' ? (
                    <div className="message-type">【文件】</div>
                  ) : message.messageType === 'location' ? (
                    <div className="message-type">【位置】</div>
                  ) : (
                    <div className="message-type">【其他】</div>
                  )}
                </div>
                <div className="result-info">
                  <div className="result-sender">
                    {message.from === currentUser.username
                      ? '我'
                      : selectedUser.username}
                  </div>
                  <div className="result-time">
                    {formatTime(message.timestamp)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default SearchChat;
